from copy import deepcopy


def classify(mb_str, code_sep='\t', is_reverse=False):
	"""fmt.classify document:
	Author: Lemonix
	Introduce: 将码表拆开分类
	Return: list[list[str]]
	Parameter:
		$mb_str: str
		$code_sep: str
		$is_reverse: bool
	Example: "jx 你" -> [ ["jx", "你"] ]
	"""

	# 前候选后码即为“反”
	if is_reverse:
		split_by_sep = lambda i: reversed(i.split(code_sep, 1))
	else:
		split_by_sep = lambda i: i.split(code_sep, 1)

	# 拆分并打包为 list 的键值对
	splited = list(map(split_by_sep, mb_str.split('\n')))

	return splited
	

def break_up(origin_splited, content_sep=' ', is_change=False):
	"""fmt.break_up document:
	Author: Lemonix
	Introduce: 将一行多个候选拆分为一个列表
	Return: list[list[str]]
	Parameter:
		$origin_splited: list[list[str]]
		$content_sep: str
		$is_change: bool
	Example: [ ["bks", "弘 隶"] ] -> [ ["bks", "弘"], ["bks", "隶"] ]
	"""

	# 是否改变原 list
	if is_change:
		splited = origin_splited
	else:
		splited = deepcopy(origin_splited)
	
	# 遍历并拆分 content
	for index, item in enumerate(splited):
		if content_sep in item[1]:
			code = item[0]
			contents = item[1].split(content_sep)
			# 删除原键值对
			splited.pop(index)
			# 在原位置添加若干键值对
			for k, v in enumerate(contents):
				splited.insert(index + k, [code, v])

	return splited


def merge(splited):
	"""fmt.merge document:
	Author: Lemonix
	Introduce: 将编码相同的候选放入一个键值对中
	Return: dict[str, list[str]]
	Paraments:
		$splited: list[list[str]]
	Example:
		( ["bks", "弘"], ["bks", "隶"] ) -> { "bks": ["弘", "隶"]] }
	"""

	merge_table = {}

	for item in splited:
		# 解构 code content
		code, content = item
		# 存在就加，不存在就创建
		if code in merge_table:
			merge_table[code].append(content)
		else:
			merge_table[code] = [content]

	return merge_table


if __name__ == '__main__':
	mb = '''g	就
jx	你
jxbh	你好 您好'''
	res = classify(mb)
	res = break_up(res)
	print(res)
	print(merge(res))